package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.bwie.exception.BusinessException;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.Result;
import com.bwie.pojo.po.DepartmentPo;
import com.bwie.pojo.po.DictPo;
import com.bwie.pojo.po.UserPo;
import com.bwie.redis.RedisConfig;
import com.bwie.service.UserService;
import com.bwie.utils.CodeGeneratorUtil;
import com.bwie.utils.MsgUtil;
import com.bwie.utils.SendMsgUtil;
import com.bwie.utils.SmsUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @ 用户业务实现层
 * @descriptions: UserServiceImpl
 * @author: LiYang
 * @date: 2025/3/14 10:14
 * @version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpServletRequest request;
    @Override
    public Result getSms(String userPhone) {
        //判断手机号是否为空
        if(StringUtils.isEmpty(userPhone)){
            throw new BusinessException("手机号为空");
        }
        Pattern compile = Pattern.compile("^1[3-9]{10}$");
        if(compile.matcher(userPhone).matches()){
            throw new BusinessException("手机号格式错误");
        }
        //去数据库查询是否有该手机号的用户
        UserPo user=userMapper.getPhone(userPhone);
        if(ObjectUtils.isEmpty(user)){
            throw new BusinessException("该用户未注册，请去注册");
        }
        JedisPool jedisPool = RedisConfig.jedisPool();
        Jedis jedis = jedisPool.getResource();
        String redisCode = jedis.get("login:sms:code:" + userPhone);
        if (StringUtils.isNotEmpty(redisCode)) {
            return Result.error("验证码已存在，请勿再次发送");
        }
        String smsCode = CodeGeneratorUtil.generateSmsCode();
        String sendTime = jedis.get("login:sms:sendTime:" + userPhone);
        if (StringUtils.isNotEmpty(sendTime)) {
            long currentTimeMillis = System.currentTimeMillis();
            long time = currentTimeMillis - Long.parseLong(sendTime);
            if (time < 3 * 60) {
                return Result.error("验证码发送频繁，请勿重新发送");
            }
        }

        String code = SmsUtil.sendSmsCode(userPhone, smsCode);
        String redisError = jedis.get("login:sms:error:" + userPhone);
        if (StringUtils.isNotEmpty(redisError)) {
            if (Integer.valueOf(redisError) > 5) {
                return Result.error("短信发送失败次数过多");
            }
        }
        if (code==null) {
            jedis.incr(redisError);
            jedis.expire("login:sms:error:" + userPhone, 60 * 5);
            return Result.error("验证码发送失败");
        }
        jedis.setex("login:sms:code:" + userPhone, 60 * 100000, smsCode);
        jedis.set("login:sms:sendTime:" + userPhone, String.valueOf(System.currentTimeMillis()));
        jedis.del("login:sms:sendTime:" + userPhone);
        RedisConfig.close(jedis, jedisPool);
        return Result.success("发送成功");
    }

    @Override
    public Result getSmsLogin(UserPo userPo) {
        if (ObjectUtils.isEmpty(userPo)) {
            throw new BusinessException("参数异常");
        }
        if (StringUtils.isEmpty(userPo.getUserPhone())) {
            throw new BusinessException("手机号为空");
        }
        if (StringUtils.isEmpty(userPo.getVercode())) {
            throw new BusinessException("手机号为空");
        }
        //去数据库查询是否有该手机号的用户
        UserPo user=userMapper.getPhone(userPo.getUserPhone());
        if(ObjectUtils.isEmpty(user)){
            throw new BusinessException("该用户未注册，请去注册");
        }
        JedisPool jedisPool = RedisConfig.jedisPool();
        Jedis jedis = jedisPool.getResource();
        String redisCode = jedis.get("login:sms:code:" + userPo.getUserPhone());
        if (StringUtils.isEmpty(redisCode)) {
            return Result.error("验证码不存在");
        }
        if(!userPo.getVercode().equals(redisCode)){
            return Result.error("验证码不正确");
        }
        request.getSession().setAttribute("user",user);
        return Result.success("登陆成功");
    }

    @Override
    @PostConstruct
    public Result getDoctor() {
        JedisPool jedisPool = RedisConfig.jedisPool();
        Jedis jedis = jedisPool.getResource();
        List<UserPo> list;
        String doctorList = jedis.get("doctorList");
        if(StringUtils.isEmpty(doctorList)){
             list=userMapper.getDoctor();
             jedis.set("doctorList", JSON.toJSONString(list));
        }else{
            list = JSON.parseArray(doctorList, UserPo.class);
        }
        return Result.success("查询成功",list);
    }

    @Override
    public Result getSex() {
        List<DictPo> list=userMapper.getSex();
        return Result.success("查询成功",list);
    }

    @Override
    @PostConstruct
    public Result getDep() {
        JedisPool jedisPool = RedisConfig.jedisPool();
        Jedis jedis = jedisPool.getResource();
        List<DepartmentPo> list;
        String DepList = jedis.get("DepList");
        if(StringUtils.isEmpty(DepList)){
            list=userMapper.getDep();
            jedis.set("DepList", JSON.toJSONString(list));
        }else{
            list = JSON.parseArray(DepList, DepartmentPo.class);
        }

        return Result.success("查询成功",list);
    }

    @Override
    public Result selectPatientName(String patientName) {
       UserPo userPo=userMapper.selectName(patientName);
        if(ObjectUtils.isNotEmpty(userPo)){
            return Result.success("用户存在",userPo);
        }else{
            return Result.error("用户不存在");
        }
    }
}
